
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function(m, i) {
    	return args[i];
    });
};

String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.ltrim = function() {
	return this.replace(/(^\s*)/g, "");
}

String.prototype.rtrim = function() {
	return this.replace(/(\s*$)/g, "");
}

String.prototype.mid = function(start, len) {
	return this.substr(start, len);
}

String.prototype.left = function(len) {
	if (isNaN(len) || len == null) {
		len = this.length;
	} else {
		if (parseInt(len) < 0 || parseInt(len) > this.length) {
			len = this.length;
		}
	}

	return this.substring(0, len);
}

String.prototype.right = function(len) {
	if (isNaN(len) || len == null) {
		len = this.length;
	} else {
		if (parseInt(len) < 0 || parseInt(len) > this.length) {
			len = this.length;
		}
	}

	return this.substring(this.length - len, this.length);
}


var Common = {
	dialog_view_: function (url, title, xy) {
		$('#dialog_view').dialog('option', 'buttons', {
			"关闭": function() { 
				$(this).dialog("close");
			},
			
			"打印": function() { 
				$.jPrintArea("#dialog_view");
			}
		});

		dialog_view(url, title, xy);
	},
	
	dialog_upload: function (url, title, xy) {
		var result = Common.result();
		$('#dialog_edit').dialog('option', 'buttons', {			
			"关闭": function() {
				$(this).dialog("close");
			},
	
			"上传": function() {
				if (!confirm("确认是否提交？")) {
					return false;
				}
				
				$('#userfile').uploadify('upload');
			}
		});
	
		dialog_edit(url, title, xy);
	},
	
	download: function (key) {
		
		if (!confirm("确认是否下载？若下载，建议先另存，再打开。")) {
			return false;
		}
		
		var url = 'mogilefs.php?do=File.download&key=' + key;
		
		jswin(url, 'save', '800x600');
		
		return true;
	},
	
	file: function (url, key) {
		if (!confirm("确认是否删除？")) {
			return false;
		}
		
		// var c6 = 'car.php?do=Car.upload&id=' + id;
		
		var file = 'mogilefs.php?do=File.file';
		var body = { };
		body.key = key;
		
		$.post(file, body, function(data) {
			// alert(data);
			$.get(url, function(data) {
				$('#dialog_edit').html(data);
			});
		});
		
		return true;
	},
	
	result: function() {
		var s = $("div[id^='result']:visible");
		
		return "#" + s[0].id;
	},
	
	ret_add: function(json) {		
		if (json == null || json == undefined) {
			alert("出现异常，请联系管理员！。");
			return;
		}
		
		if (json.status == 1) {
			alert("添加数据成功！");
			return;
		}
		
		if (json.status > 0) {
			var fmt = "成功添加{0}条数据，请重新查找。";
			var msg = fmt.format(json.status);
			alert(msg);
			return;
		}
		
		alert("出现异常，请联系管理员！。");
	},
	
	supplier: function (id) {
		var url = "contact.php?do=Supplier.view&small=on&id=" + id;

		_dialog_view(url, '供应商', '600x400');
	},
	
	express: function (id) {
		var url = "contact.php?do=Express.view&small=on&id=" + id;

		_dialog_view(url, '货运公司', '600x400');
	},
	
	emp: function (id) {
		var url = "emp.php?do=Emp.view&id=" + id;
		$('#dialog_emp').dialog('option', 'buttons', { 		
			"关闭": function() { 
				$(this).dialog("close");
			}
		});

		dialog_x(url, '员工信息', '500x300', '#dialog_emp');
	},

	customer: function (id) {
		var url = "contact.php?do=Customer.view&small=on&id=" + id;
		_dialog_view(url, '客户信息', '600x400');
	},	

	mold: function (id) {
		var url = "mold.php?do=Mold.view&id=" + id;
		
		_dialog_view(url, '产品信息', '550x320');
	},

	material: function (id) {
		var url = "material.php?do=Material.view&id=" + id + "&bt=1";
		
		_dialog_view(url, '材料信息', '600x360');
	},

	car: function (id) {
		var url = "car.php?do=Car.view&id=" + id;
		
		_dialog_view(url, '车辆信息', '600x360');
	},

	machine: function (id) {
		var url = "info.php?do=Machine.view&id=" + id;
		
		_dialog_view(url, '机器信息', '600x360');
	},

	collapse: function (cc) {
		$(cc).toggle();
		
		if ($(cc).hasClass("ui-icon-circle-triangle-w")) {
			$(cc).removeClass("ui-icon-circle-triangle-w").addClass("ui-icon-circle-triangle-s");			
		} else {
			$(cc).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-w");
		}	 
	},
	
	collapse2: function (cc) {
		var a = $("table[id^='find_']:visible tr");
				
		var b = $("table[id^='find_']:visible tr:last");
		if ($(cc).hasClass("ui-icon-circle-triangle-n")) {
			a.hide();
			b.show();
			$(cc).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-e");
		} else {
			a.show();
			$(cc).removeClass("ui-icon-circle-triangle-e").addClass("ui-icon-circle-triangle-n");
		}

		return false;
	},
	
	toggle: function (cc, dd) {
		// $("#label_linkman").toggle();
		$(dd).toggle();
		
		if ($(cc).hasClass("ui-icon-circle-triangle-w")) {
			$(cc).removeClass("ui-icon-circle-triangle-w").addClass("ui-icon-circle-triangle-s");			
		} else {
			$(cc).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-w");
		}	 
	},
	
	call: function (number) {
		$('#dialog_add').dialog('option', 'buttons', {
			"关闭": function() {
				$(this).dialog("close");
			},

			"开始拔打": function() {
				if (!confirm("确认是否开始拔打？")) {
					return false;
				}
				
				var form = $("#form_add")[0];

				var body = { };
				body.call = form.call.value;			
				body.number = form.number.value;
				body.exten = form.exten.value;

				$(this).dialog("close");

				$.post('tel.php?do=Call.addPost', body, function(data) {
					alert("正在拔打。。。");
				});
			}
		});

		var url = "tel.php?do=Call.add&number=" + encodeURIComponent(number);
		dialog_add(url, '拔打电话', '450x270');
	},
	
	number: function (e, number, cdr) {
		
		var body = { };
		body.cdr = cdr;
		body.number = number;
		
		$.getJSON('tel.php?do=Cdr.ajax_number', body, function(json) {
			// alert($.toJSON(json));
			if (json.t == 'exten') {
				// alert("exten");
				emp(json.id);
			} else if (json.t == 'emp') {
				// alert("emp");
				emp(json.id);
			} else if (json.t == 'contact') {
				// alert("contact");
				Common.contact(e, json);
				// Cdr.contact(e, json.id, json.info, json.info_id);
			}

			return false;
		});
	},

	contact: function (e, json) {
		
		var id = json.id;
		var info = json.info;
		var info_id = json.info_id;
		
		var c1 = 'contact.php?do=Customer.view&id=' + info_id;
		var c2 = 'contact.php?do=Supplier.view&id=' + info_id;

		var c8 = 'info.php?do=Contact.view&id=' + id;
		
		var a1 = ['客户信息', 'url', 'Common.dialog_view_', '650x420'];
		var a2 = ['供应商', 'url', 'Common.dialog_view_', '650x420'];

		var a8 = ['联系信息', 'url', 'Common.dialog_view_', '650x400'];
		
		if (info == 1) {
			var s = c1 + ", " + c8;

			return popup(e, [a1, a8], s);
		}

		if (info == 2) {
			var s = c2 + ", " + c8;

			return popup(e, [a2, a8], s);
		}

		var s = c8;

		return popup(e, [a8], s);
	},
	
	fax: function (number) {
		$('#dialog_add').dialog('option', 'buttons', {
			"关闭": function() {
				$(this).dialog("close");
			},

			"发送传真": function() {
				if (!confirm("确认是否发送传真？")) {
					return false;
				}
								
				var form = $("form[id^='form_add']:visible")[0];
				
				var to = form.to.value;
				if (is_null(to)) {
					alert("传真号码不能为空！");
					return false;
				}
				
				var queryString = $("form[id^='form_add']:visible").formSerialize();
				// alert(queryString);
				
				var s = "fax.php?do=Fax.ajax_upload&" + queryString;
				$("input[id^='userfile']:visible").uploadifySettings('script', s);
				$("input[id^='userfile']:visible").uploadifyUpload();
				
				alert("发送成功！");				
			}
		});

		var url = "fax.php?do=Fax.send&number=" + encodeURIComponent(number);
		dialog_add(url, '发送传真', '550x380');
	},
	
	call2: function (from, number) {
		$('#dialog_add').dialog('option', 'buttons', {
			"关闭": function() {
				$(this).dialog("close");
			},

			"开始拔打": function() {
				if (!confirm("确认是否开始拔打？")) {
					return false;
				}
				
				var form = $("#form_add")[0];

				var body = { };
				body.call = form.call.value;			
				body.number = form.number.value;
				body.exten = form.exten.value;

				$(this).dialog("close");

				$.post('/t/portal/?do=Call.addPost', body, function(data) {
					alert("正在拔打。。。");
				});
			}
		});

		var url = "/t/portal/?do=Call.add&from=" + encodeURIComponent(from) + "&number=" + encodeURIComponent(number);
		dialog_add(url, '拔打电话', '450x260');
	},
	
	payment_x: function(form) {
		var payment = form.payment.value;
		
		var payment_x = {};
		if (payment == '1' || payment == '3') {			
			payment_x.name = form.z_name.value;
			payment_x.tel = form.z_tel.value;
			payment_x.mobile = form.z_mobile.value;
			payment_x.content = form.z_content.value;
		} else if (payment == '2' || payment == '4') {
			if (is_null(form.x_bank.value) || is_null(form.x_name.value) || is_null(form.x_code.value)) {
				alert("银行信息不能为空！");
				return false;				
			}
			
			x_code = form.x_code.value;
			// alert(x_code);
			x_code = x_code.replace(/\s/g, "");
			// alert(x_code);
			
			payment_x.bank = form.x_bank.value;
			payment_x.name = form.x_name.value;
			payment_x.code = x_code;
			payment_x.content = form.x_content.value;
		} 
		
		return $.toJSON(payment_x);
	},
	
	copy: function(txt) {
		if (window.clipboardData) {
			window.clipboardData.clearData();
			window.clipboardData.setData("Text", txt);
		} else if (navigator.userAgent.indexOf("Opera") != -1) {
			window.location = txt;
		} else if (window.netscape) {
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			} catch (e) {
				alert("被浏览器拒绝！\n请在浏览器地址栏输入\"about:config\"并回车\n然后将\"signed.applets.codebase_principal_support\"设置为\"true\"");
			}

			var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
			if (!clip) {
				return;
			}

			var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
			if (!trans) {
				return;
			}

			trans.addDataFlavor("text/unicode");
			var str = new Object();
			var len = new Object();
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			var copytext = txt;
			
			str.data = copytext;
			trans.setTransferData("text/unicode", str, copytext.length * 2);
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip) {
				return false;
			}
			
			clip.setData(trans, null, clipid.kGlobalClipboard);
			
			var msg = "\"" + txt + "\", 复制成功！";
			alert(msg);
		}
	},
	
	list_delete: function (url, view) {
		var result = Common.result();
		
		var c = new Array();
		$("input[name^='c_']").each(function() {
			if ($(this).attr("checked")) {
				var s = encodeURIComponent(this.name) + "=" + encodeURIComponent($(this).val());
				c.push(s);
			}
		});
		
		var body = c.join("&");
		
		if (confirm("您确定删除已选择的" + c.length + "条记录吗？")) {
			// $.blockUI({ message: $('#loading') });

			$.get(url, body, function(data) {
				$(result).html(data);
			});
			
			return true;
		}
	},
	
	dialog_txt: function (url, title, xy) {
		var c = new Array();
		$("input[name^='c_']").each(function() {
			if ($(this).attr("checked")) {
				var s = encodeURIComponent(this.name) + "=" + encodeURIComponent($(this).val());
				c.push(s);
			}
		});
		
		var cc = c.join("&");
		
		var s = url + "&" + cc;
		
		jswin(s, 'jswin', '1024x768');
	},
	
	customer_x: function(form) {		
		var customer_x = {};				
		customer_x.name = form.a_name.value;
		customer_x.fullname = form.a_fullname.value;
		customer_x.address = form.a_address.value;				
		customer_x.web = form.a_web.value;
		
		customer_x.contact = form.a_contact.value;
		customer_x.mobile = form.a_mobile.value;
		customer_x.tel = form.a_tel.value;
		customer_x.fax = form.a_fax.value;
		customer_x.email = form.a_email.value;
		customer_x.content = form.a_content.value;		
		
		return $.toJSON(customer_x);
	},
	
	linkman: function (a) {		
		$select = $("#a_linkman");		
		$select.empty();
		count = 0;
		$.each(a, function(k, v) {
	    	var item = new Option(v.name, v.id);
	    	$select[0].options.add(item);
	    	
	    	if (count == 1) {
	    		Common._link_man(v.id, false);
	    	}
	    	
	    	count++;
	    });
		
		$select.change(function() {
			var id = $(this).val();
			Common._link_man(id, true);
		}); 
	},

	_link_man: function (id, select) {
		var url = 'info.php?do=Contact.ajax_id&q=' + id;
		$.getJSON(url, function(json) {
			var aaa = Common.aaa();
			if (select || aaa) {
				$("#a_contact").val(json.name);
				$("#a_mobile").val(json.mobile);
				$("#a_tel").val(json.tel);
				$("#a_fax").val(json.fax);
				$("#a_email").val(json.email);
			}
		});
	},
	
	aaa: function() {
		if ($("#a_contact").val().trim() != "") {
			return false;
		}
		 
		if ($("#a_mobile").val().trim() != "") {
			return false;
		} 
		
		if ($("#a_tel").val().trim() != "") {
			return false;
		}
		
		if ($("#a_fax").val().trim() != "") {
			return false;
		}
		
		if ($("#a_email").val().trim() != "") {
			return false;
		}
		
		return true;
	}
};

var Currency = {
	upper: function (s, b, label) {
		s = s.toString();	
		if (s == "") {
			return "";
		}/*
		
		if (s.match(/[^,.\d|-]/) != null) {
			return "";
		}
		
		if (s.match(/^(([-\d{1,3}(,\d{3})|\d{1,3}(,\d{3})]*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
			return "";
		}*/
		
		var r = Currency._upper(s);
		
		// var s = $("#label_amount");		
		$(label).text("（大写）" + b + " " + r);
	},
	
	_upper: function (s) {
		s = s.replace(/,/g, '');
		
		s = Math.abs(s);
		
		// Constants:
		var MAXIMUM_NUMBER = 99999999999.99;
		
		// Predefine the radix characters and currency symbols for output:
		var CN_ZERO = "零";
		var CN_ONE = "壹";
		var CN_TWO = "贰";
		var CN_THREE = "叁";
		var CN_FOUR = "肆";
		var CN_FIVE = "伍";
		var CN_SIX = "陆";
		var CN_SEVEN = "柒";
		var CN_EIGHT = "捌";
		var CN_NINE = "玖";
		var CN_TEN = "拾";
		var CN_HUNDRED = "佰";
		var CN_THOUSAND = "仟";
		var CN_TEN_THOUSAND = "万";
		var CN_HUNDRED_MILLION = "亿";
		
		var CN_SYMBOL = "人民币";
		
		var CN_DOLLAR = "元";
		var CN_TEN_CENT = "角";
		var CN_CENT = "分";
		var CN_INTEGER = "整";

		// Variables:
		var integral; // Represent integral part of digit number.
		var decimal; // Represent decimal part of digit number.
		
		var parts;
		var digits, radices, bigRadices, decimals;
		var zeroCount;
		var i, p, d;
		var quotient, modulus;

		// Validate input string:
		s = s.toString();	
		if (s == "") {
			// alert("Empty input!");
			return "";
		}
		
		if (s.match(/[^,.\d]/) != null) {
			// alert("Invalid characters in the input string!");
			return "";
		}
		
		if (s.match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
			// alert("Illegal format of digit number!");
			return "";
		}

		// Normalize the format of input digits:
		s = s.replace(/,/g, ""); // Remove comma
															// delimiters.
		s = s.replace(/^0+/, ""); // Trim zeros at the
															// beginning.
		
		// Assert the number is not greater than the maximum number.
		if (Number(s) > MAXIMUM_NUMBER) {
			alert("Too large a number to convert!");
			return "";
		}
		
		var s2 = Math.abs(Number(s)).toString();
		if (s != s2) {
			s = s2;
		}

		// Process the coversion from currency digits to characters:
		// Separate integral and decimal parts before processing coversion:
		parts = s.split(".");
		if (parts.length > 1) {
			integral = parts[0];
			decimal = parts[1];
			// Cut down redundant decimal digits that are after the second.
			decimal = decimal.substr(0, 2);
		} else {
			integral = parts[0];
			decimal = "";
		}
		
		// Prepare the characters corresponding to the digits:
		digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE,
				CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
		radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
		bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
		decimals = new Array(CN_TEN_CENT, CN_CENT);
		
		// Start processing:
		var ret = "";
		
		// Process integral part if it is larger than 0:
		if (Number(integral) > 0) {
			zeroCount = 0;
			for (i = 0; i < integral.length; i++) {
				p = integral.length - i - 1;
				d = integral.substr(i, 1);
				quotient = p / 4;
				modulus = p % 4;
				if (d == "0") {
					zeroCount++;
				} else {
					if (zeroCount > 0) {
						ret += digits[0];
					}
					zeroCount = 0;
					ret += digits[Number(d)] + radices[modulus];
				}
				if (modulus == 0 && zeroCount < 4) {
					ret += bigRadices[quotient];
				}
			}
			
			ret += CN_DOLLAR;
		}
		
		// Process decimal part if there is:
		if (decimal != "") {
			for (i = 0; i < decimal.length; i++) {
				d = decimal.substr(i, 1);
				if (d != "0") {
					ret += digits[Number(d)] + decimals[i];
				} else {
					ret += CN_ZERO;
				}
			}
		}
		
		// Confirm and return the final output string:
		if (ret == "") {
			ret = CN_ZERO + CN_DOLLAR;
		}
		
		if (decimal == "") {
			ret += CN_INTEGER;
		}
		
		// ret = CN_SYMBOL + ret;
		
		return ret;
	}
};

var Tip = {
	emp: function (name) {
		/*
		$("input[id^='emp']:visible").tooltip({
			items: "input[id^='emp']:visible",
			content: function() {
				var fmt = "请输入{0}姓名拼音首字母，然后选择并回车即可，如李四，输入ls；若为离职人员，请输入3ls";
				var emp_s = fmt.format("员工");
				if (!is_null(name)) {
					emp_s = fmt.format(name);
				}
				
				return emp_s;
			},
			
			position : {
				my : "left top",
				at : "right bottom+5"
			}
		});*/
		
		$("input[id^='emp']:visible").autocomplete(Test.emp);
		
		_ck_default("input[id^='emp']:visible", "input[id^='t_emp']:visible");
	},
	
	oper: function () {
		$("input[id^='oper']:visible").tooltip({
			items: "input[id^='oper_s']:visible",
			content: function() {
				var fmt = "请输入{0}姓名拼音首字母，然后选择并回车即可，如李四，输入ls；若为离职人员，请输入3ls";
				var oper_s = fmt.format("录入员");
				
				return oper_s;
			},
			
			position : {
				my : "left top",
				at : "right bottom+5"
			}
			
		});
		
		$("input[id^='oper']:visible").autocomplete(Test.emp);
		
		_ck_default("input[id^='oper']:visible", "input[id^='oper_t']:visible");
	},
	
	supplier: function() {
		$("input[id^='supplier']:visible").tooltip({
			items: "input[id^='supplier']:visible",
			content: function() {
				return '请输入供应商名称拼音首字母，然后选择并回车即可。如明利，输入ml';
			},
			
			position : {
				my : "left top",
				at : "right bottom+5"
			}
			
		});

		$("input[id^='supplier']:visible").autocomplete(Test.supplier);
	},
	
	dept: function() {
		$("input[id^='dept']:visible").tooltip({
			items: "input[id^='dept']:visible",
			content: function() {
				return '请输入部门名称拼音首字母，然后选择并回车即可。如行政，输入xz';
			},
			
			position : {
				my : "left top",
				at : "right bottom+5"
			}
			
		});
		
		$("input[id^='dept']:visible").autocomplete(Test.dept);
	}
};
